package com.yeban.javase.day17.sync;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/31
 */
public class House {

    private int num = 0;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    // 生产货物
    public void store() {
        lock.lock();
        try {
            // 生产者被唤醒后，还需要进行判断。用while代替if为了出现假唤醒的情况
            while (num >= 1) {
                System.out.println("仓库已满, 生产者需要进入等待~");
                condition.await();
            }
            // 进入生产
            System.out.println(Thread.currentThread().getName() + "生产了" + (++num));
            // 唤醒所有线程
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    // 销售货物
    public void sale() {
        lock.lock();
        try {
            while(num <= 0) {
                System.out.println("仓库已空，消费者需要进入等待~");
                condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "生产了" + (num--));
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
